#!/usr/bin/env python
# -*- coding: utf-8 -*-

# 导入相应的库文件
import urllib.request
import requests
import os
import re
import openpyxl
import mysql
import mysql.connector
from threading import Thread

# base_dir="E:\data\小说\\"
get_file_sql = 'select * from fiction_table where download is null and type_id in (10,11,14) order by rand() limit '
update_sql = 'update fiction_table set download=1 where id = '


def down_file(i):
    mydb = mysql.connector.connect(
        host="165.135.111.114",  # 数据库主机地址
        port='31004',
        user="root",  # 数据库用户名
        database="test",  # 数据库名称 没有的话插入操作报错
        passwd="211314wccA"  # 数据库密码

    )
    mycursor = mydb.cursor()
    mycursor.execute(get_file_sql+i.__str__())
    results = mycursor.fetchall()
    for row in results:
        id = row[0]
        f_name = row[1]
        f_code = row[2]
        type_id = row[3]
        type_name = row[4]
        download = row[5]
        # 打印结果
        print("id=%s,f_name=%s,f_code=%s,type_id=%s,type_name=%s,download=%s" % \
              (id, f_name, f_code, type_id, type_name, download))
        download_file_to_dir(f_name,type_name,f_code)
        mycursor.execute(update_sql+id.__str__())
        mydb.commit()


def download_file_to_dir(file_name,type,id):
    url = "https://down7.ixdzs8.com/" + str(id) + ".zip"
    print("下载url: "+url)
    try:
        if not os.path.exists('./' + type + '/'):
            os.makedirs('./' + type + '/')
        print('./' + type + '/' + file_name + ".zip")
        urllib.request.urlretrieve(url, './' + type + '/' + file_name + ".zip")
    except Exception as e:
        print("===捕获异常" + e.__str__())

# 程序主入口
if __name__ == '__main__':
    # test("https://ixdzs8.com/sort/11/")
    thread1 = Thread(target=down_file, args=(150,))
    # thread2 = Thread(target=geturl_into_excel, args=(7,))
    # thread3 = Thread(target=geturl_into_excel, args=(8,))
    # thread4 = Thread(target=geturl_into_excel, args=(9,))
    # thread5 = Thread(target=geturl_into_excel, args=(10,))

    thread1.start()
    # thread2.start()
    # thread3.start()
    # thread4.start()
    # thread5.start()
